package servlet;


import bean.CustomerBean;
import bean.WarehouseBean;
import com.alibaba.fastjson.JSON;
import util.JdbcUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

public class CustomerHuntServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int cid;
        String name =request.getParameter("name");
        //处理中文乱码问题
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        //获取传进来的cid和name
        try{
            cid = Integer.parseInt(request.getParameter("cid"));
            if(name==""){
                name="@";
             }
         }catch (Exception e){
            cid=0;
        }

        //获取模糊查询的数据
        String sql="SELECT * FROM customer where cid like  ? or  name like  ?";

        try {
            PreparedStatement ps = JdbcUtil.getConnection().prepareStatement(sql);
            ps.setInt(1,cid);
            ps.setString(2, "%"+name+"%");
            ResultSet set=ps.executeQuery();
            ArrayList<CustomerBean> arr = new ArrayList<CustomerBean>();
            while (set.next()){
                CustomerBean cu = new CustomerBean();
                cu.setCid(set.getInt(1));
                cu.setName(set.getString(2));
                cu.setPerson(set.getString(3));
                cu.setTel(set.getString(4));
                cu.setEmail(set.getString(5));
                cu.setAddress(set.getString(6));
                arr.add(cu);
            }
            String json = JSON.toJSONString(arr);
            out.print(json);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

